import Vue from 'vue';

const textEllipsis = {
    inserted(el, binding) {
        const { value = '', arg } = binding;
        const { fontSize = 16, maxLines = 1, width = el.parentNode.offsetWidth } = arg;
        // 单行直接用css控制
        if (maxLines === 1) {
            el.style.overflow = 'hidden';
            el.style.whiteSpace = 'nowrap';
            el.style.textOverflow = 'ellipsis';
            el.style.wordWrap = 'normal';
            el.innerText = value;
            return true;
        }
        // 一行最多多少字
        const lineWordCount = Math.floor(width / fontSize);
        // 最大多少字
        const maxWordCount = lineWordCount * maxLines;
        if (value.length > maxWordCount) {
            el.innerText = value.substring(0, maxWordCount) + '...';
        } else {
            el.innerText = value;
        }
        return true;
        // const width = el.parentNode.offsetWidth;
    }
};

Vue.directive('ellipsis', textEllipsis);
